package testview.zhen.com.myapplication.mvvm

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.*
import androidx.work.*
import com.ldr.base_library.mvvm.BaseActivity
import kotlinx.coroutines.launch
import testview.zhen.com.myapplication.databinding.ActivityWorkersBinding
import testview.zhen.com.myapplication.jetpack.BtnTwoWorker
import testview.zhen.com.myapplication.jetpack.DelayWorker
import testview.zhen.com.myapplication.jetpack.MainWorker

/**
 * Create by ldr
 * on 2019/10/14 11:27.
 */
class WorkerActivity : BaseActivity<ActivityWorkersBinding, WorkerViewModel>() {

    override val mViewModel: WorkerViewModel by viewModels()
    init{
        //这个只会运行一次！！！！！请记住，如果活动重新启动，协程将不会重新启动。（官网的翻译）
        lifecycleScope.launch{
            whenCreated {
                Log.i("WorkerActivity","whenCreated")
            }
            whenStarted {
                Log.i("WorkerActivity","whenStarted")
            }
            whenResumed{
                Log.i("WorkerActivity","whenResumed")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        //1.1 基础调用
        binding.work1Btn.setOnClickListener {
            val baseWork = OneTimeWorkRequest.Builder(MainWorker::class.java).build()
            WorkManager.getInstance().enqueue(baseWork)
        }
        //1.2 监听数据调用方式
        binding.work2Btn.setOnClickListener {

            //1 构建 Data数据
            var data = Data.Builder().putString("LiveDataTest","有生命的数据监听··").build()

            //2 构建work
            val liveDataWork = OneTimeWorkRequest.Builder(BtnTwoWorker::class.java)
                    .addTag("TAG")
                    .setInputData(data)
                    .build()

            //3 通过work的id获取Status
           val status =  WorkManager.getInstance().getWorkInfoByIdLiveData(liveDataWork.id)

            //监听状态以及数据的变化
            //注意一点：这里的监听的时候 状态改变Observer就会跑一遍~~
           status.observe(this, Observer {
               if(it.state == WorkInfo.State.SUCCEEDED){
                   mViewModel.data.value = it.outputData.getString("LiveDataTest")
                   Log.i("WorkerActivity", it.outputData.getString("LiveDataTest")?:"空")
               }
               Log.i("WorkerActivity",it.state.name)
               Log.i("WorkerActivity","${it.state.isFinished}")
            })
            WorkManager.getInstance().enqueue(liveDataWork)
        }
        var workConstrains:OneTimeWorkRequest
        //1 增加约束条件
        val constrains = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
        //2 构建 Data数据
        var data = Data.Builder().putString("delayWork","延时操作~~~").putInt("time",10).build()
        //3 构建workRequest
        workConstrains =  OneTimeWorkRequest.Builder(DelayWorker::class.java).setConstraints(constrains)
                .setInputData(data)
                .build()

        //1.3 任务约束
        binding.work3Btn.setOnClickListener {

            //4 获取Status监听数据
            val status = WorkManager.getInstance().getWorkInfoByIdLiveData(workConstrains.id)
            status.observe(this, Observer {
                binding.text1.text = it.outputData.getString("LiveDataTest")
                Log.i("WorkerActivity",it?.state?.name?:"")
                if (it?.state!!.isFinished) {
                    Log.e("TestWorker", "Finish")
                }
            })
            //5 添加到equque
            Log.i("delayWork","装入队列~~~~~~")
            WorkManager.getInstance().enqueue(workConstrains)
        }
        //取消任务
        binding.cancelBtn.setOnClickListener {
            Log.i("delayWork","取消任务~~~~~~")
            WorkManager.getInstance().cancelWorkById(workConstrains.id)
        }

        binding.coroutineBtn.setOnClickListener {
            mViewModel.viewModelScope.launch {
            }

        }
    }

    private fun initViewModel() {
        //创建监听 更新UI
        mViewModel.id.observe(this, Observer {
            binding.text1.text = it
        })
        mViewModel.data.observe(this, Observer {
            binding.text2.text = it
        })

    }


    override fun onError(e: Throwable) {
        super.onError(e)
    }

}

